package cn.wangqi.personal.common;/*
 *The code is written by 51jiecai.com.
 *All rights reserved.
 */


import cn.wangqi.personal.util.Page;
import cn.wangqi.personal.util.ResultModel;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class BaseController {

    public static final ObjectMapper JSON_MAPPER_NOTNULL = new ObjectMapper();

    protected String buildErrorResponse(String msg) {
        return buildErrorResponse(msg, null);
    }

    protected <T extends Serializable> String buildErrorResponse(String msg, T obj) {
        ResultModel<T> model = new ResultModel<T>();
        model.setCode(ResultModel.RESULT_ERROR);
        model.setMsg(msg);
        model.setData(obj);
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected String buildNoPermissionResponse() {
        return buildNoPermissionResponse("没有权限访问");
    }

    protected String buildNoPermissionResponse(String msg) {
        ResultModel<String> model = new ResultModel<String>();
        model.setCode(ResultModel.RESULT_NOPERMISSION);
        model.setMsg(msg);
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected String buildLimitResponse() {
        return buildLimitResponse("访问过于频繁，请稍后再试!");
    }

    protected String buildLimitResponse(String msg) {
        ResultModel<String> model = new ResultModel<String>();
        model.setCode(ResultModel.RESULT_NOPERMISSION);
        model.setMsg(msg);
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected <T extends Serializable> String buildLimitResponse(String msg, T obj) {
        ResultModel<T> model = new ResultModel<T>();
        model.setCode(ResultModel.RESULT_NOPERMISSION);
        model.setMsg(msg);
        model.setData(obj);
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected String buildAuthInvalidResponse(String msg) {
        ResultModel<String> model = new ResultModel<String>();
        model.setCode(ResultModel.RESULT_AUTH_INVALID);
        model.setMsg(msg);
        try {
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected String buildSuccessResponse() {
        return buildSuccessResponse(null);
    }

    protected <T extends Serializable> String buildSuccessResponse(T obj) {
        ResultModel<T> model = new ResultModel<T>();
        model.setCode(ResultModel.RESULT_SUCCESS);
        model.setData(obj);
        try {
            JSON_MAPPER_NOTNULL.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            return JSON_MAPPER_NOTNULL.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Json process Exception:" + e.getMessage(), e);
        }
    }

    protected boolean isMoblieClient(HttpServletRequest request) {
        boolean flag = false;
        String agent = request.getHeader("user-agent");
        String[] keywords = {"Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser"};
        if (!agent.contains("Windows NT") ||
                (agent.contains("Windows NT") && agent.contains("compatible; MSIE 9.0;"))) {
            if (!agent.contains("Windows NT") && !agent.contains("Macintosh")) {
                for (String item : keywords) {
                    if (agent.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    protected final static int DEFAULT_PAGE_SIZE = 10;

    protected Page genPage(int start, int pageSize) {
        Page page = new Page();
        if (start < 0) {
            start = 0;
        }
        if (pageSize <= 0) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        page.setStart(start);
        page.setPageSize(pageSize);
        return page;
    }

    protected Page genPage(int currentPage) {
        int start = (currentPage - 1) * DEFAULT_PAGE_SIZE;
        return genPage(start, DEFAULT_PAGE_SIZE);
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /****
     * 当页面表单中有若干个相同name的checkbox时，layui自动上传上来的参数中，获取参数列表的公用方法
     * @param request
     * @param paramName
     * @return
     */
    protected String[] getParamArray(HttpServletRequest request, String paramName){
        Objects.requireNonNull(paramName);
        Objects.requireNonNull(request);
        String[] temp = request.getParameterValues(paramName + "[]");
        if(temp != null) {
            return temp;
        }
        //如果上面的temp1为null,说明checkbox个数为1或0，这种情况下，如下处理
        String value = request.getParameter(paramName);
        if(value == null) {
            return new String[]{};
        }
        temp = new String[]{request.getParameter(paramName)};
        return temp;
    }
}
